<template>
  <div class="lg-container" v-wechat-title="$route.meta.title" v-if="isTemplate">
    <h2 class="van-doc-demo-block__title">基础信息</h2>
    <van-cell-group>
      <van-field v-model="data.name" required clearable label="姓名:" placeholder="请输入姓名" />
      <div class="van-cell van-cell--required van-field">
        <div class="van-cell__title van-field__label">
          <span>性别:</span>
        </div>
        <div class="van-cell__value">
          <van-radio-group class="lg-radio-group" v-model="data.sex" @change="sexChange">
            <van-radio
              checked-color="#03A9AC"
              v-for="item in sexList"
              :key="item.key"
              :name="item.key"
            >{{item.valueCn}}</van-radio>
          </van-radio-group>
        </div>
      </div>
      <van-field
        v-model="data.birthday"
        required
        readonly
        label="出生日期:"
        @click="birthdayClick"
        placeholder="请选择出生日期"
      />
      <van-field v-model="data.phone" required clearable label="手机号:" placeholder="请输入手机号" />
      <div class="van-cell van-cell--required van-field">
        <div class="van-cell__title van-field__label">
          <span>患者分类:</span>
        </div>
        <div class="van-cell__value" @click="typeClick">
          <div class="lgLabel" v-if="data.label">{{data.label}}</div>
          <div v-else class="placeholder-class">请选择患者分类</div>
        </div>
      </div>
      <div class="van-cell van-field">
        <div class="van-cell__title van-field__label">
          <span>婚否:</span>
        </div>
        <div class="van-cell__value">
          <van-radio-group class="lg-radio-group" v-model="data.marryStatus">
            <van-radio
              checked-color="#03A9AC"
              v-for="item in marryStatusList"
              :key="item.key"
              :name="item.key"
            >{{item.valueCn}}</van-radio>
          </van-radio-group>
        </div>
      </div>
      <van-field v-model="data.idCard" clearable label="身份证号:" placeholder="请输入身份证号" />
      <van-field
        v-model="data.healthCareCardNumber"
        type="number"
        clearable
        label="医保卡号:"
        placeholder="请输入医保卡号"
      />
    </van-cell-group>
    <h2 class="van-doc-demo-block__title">患者家属</h2>
    <van-cell-group>
      <van-field
        v-model="data.patientRef[0].name"
        clearable
        label="1.联系人姓名:"
        placeholder="请输入联系人姓名"
      />
      <van-field
        v-model="data.patientRef[0].relation"
        clearable
        label="与患者关系:"
        placeholder="请输入联系人与患者关系"
      />
      <van-field
        v-model="data.patientRef[0].phone"
        clearable
        label="联系人电话:"
        placeholder="请输入联系人电话"
      />
      <van-field
        v-model="data.patientRef[1].name"
        clearable
        label="2.联系人姓名:"
        placeholder="请输入联系人姓名"
      />
      <van-field
        v-model="data.patientRef[1].relation"
        clearable
        label="与患者关系:"
        placeholder="请输入联系人与患者关系"
      />
      <van-field
        v-model="data.patientRef[1].phone"
        clearable
        label="联系人电话:"
        placeholder="请输入联系人电话"
      />
    </van-cell-group>
    <h2 class="van-doc-demo-block__title">病例信息</h2>
    <van-cell-group>
      <van-field v-model="data.visitHospital" clearable label="就诊医院:" placeholder="请输入就诊医院" />
      <van-field
        v-model="data.medicalCardNumber"
        type="number"
        clearable
        label="就诊卡号:"
        placeholder="请输入就诊卡号"
      />
      <van-field
        v-model="data.operationTime"
        readonly
        label="手术时间:"
        @click="operationTimeClick"
        placeholder="请选择手术时间"
      />
      <van-field v-model="data.operationName" clearable label="手术名称:" placeholder="请输入手术名称" />
      <van-field v-model="data.diagnosis" clearable label="诊断:" placeholder="请输入诊断" />
      <van-field
        v-model="data.baseInfo"
        rows="2"
        autosize
        label="基本病情:"
        type="textarea"
        maxlength="200"
        placeholder="请输入基本病情"
        show-word-limit
      />
    </van-cell-group>
    <van-button type="primary" class="lg-patientInfo-btn" @click="onSave" color="#03A9AC">保存</van-button>
    <van-popup v-model="isShow" position="bottom" :style="{ height: '40%' }">
      <div v-if="showText === 'type'" class="lg-checkbox-content">
        <div class="van-hairline--top-bottom van-picker__toolbar">
          <button class="van-picker__cancel" @click="onCancel">取消</button>
          <button class="van-picker__confirm" @click="onTypeConfirm">确认</button>
        </div>
        <van-picker :columns="columns" @change="onTypeChange" />
      </div>
      <van-datetime-picker
        v-else
        v-model="currentDate"
        :min-date="minDate"
        @confirm="onBirthdayConfirm"
        @cancel="onCancel"
        type="date"
      />
    </van-popup>
  </div>
</template>
<script>
// import OSS from 'ali-oss'
import axios from 'axios'
import { getAllDicByType, getOssPolicy } from '@/api/common'
import { readInfo, createOrUpdateInfo, getDepartmentList } from '@/api/info'
export default {
  data () {
    return {
      apiName: 'patient',
      isShow: false,
      isTemplate: false,
      showText: '',
      currentDate: new Date(),
      minDate: new Date(1900, 0, 1),
      sexList: [],
      marryStatusList: [],
      typeList: [],
      columns: [
        {
          values: [],
          className: 'column1',
          defaultIndex: 0
        },
        {
          values: [],
          className: 'column2',
          defaultIndex: 0
        }
      ],
      data: {
        id: null,
        openId: '',
        name: '',
        sex: 0,
        sexShow: '',
        birthday: '',
        phone: '',
        label: '',
        marryStatus: '',
        idCard: '',
        healthCareCardNumber: '',
        patientRef: [
          {
            name: '',
            phone: '',
            relation: '',
            patientId: ''
          },
          {
            name: '',
            phone: '',
            relation: '',
            patientId: ''
          }
        ],
        visitHospital: '',
        medicalCardNumber: '',
        operationTime: '',
        operationName: '',
        diagnosis: '',
        baseInfo: '',
        medicalUrl: [],
        selectVal: [0, 0]
      }
    }
  },
  created () {
    if (this.$route.query.openId) {
      this.data.openId = this.$route.query.openId
      this.getInfo()
      this.getAllDicByType()
    }
  },
  methods: {
    getInfo () {
      readInfo(this.data.openId).then(res => {
        if (res.code === 200) {
          if (res.status === '1') {
            this.$dialog.confirm({
              title: '提示',
              message: '暂未绑定医生，请前往绑定',
              showCancelButton: false,
              confirmButtonColor: '#03A9AC'
            }).then(() => {
              this.$router.push('/infoBound?openId=' + this.data.openId)
            }).catch(() => {
            })
          } else {
            this.isTemplate = true
            this.disposeInfo(res.info)
          }
        }
      })
    },
    disposeInfo (data) {
      this.$toast.clear()
      for (let key in data) {
        if (this.data.hasOwnProperty(key)) {
          if (data[key] || data[key] === 0) {
            this.data[key] = data[key]
          } else {
            this.data[key] = ''
          }
        }
        if (this.data.patientRef.length === 0) {
          this.data.patientRef = [
            {
              name: '',
              phone: '',
              relation: ''
            },
            {
              name: '',
              phone: '',
              relation: ''
            }
          ]
        } else if (this.data.patientRef.length === 1) {
          this.data.patientRef = [
            this.data.patientRef[0],
            {
              name: '',
              phone: '',
              relation: ''
            }
          ]
        }
      }
      this.getTypeList()
    },
    getAllDicByType () {
      this.$toast.loading({
        message: '加载中...',
        forbidClick: true,
        overlay: true,
        duration: 0
      })
      getAllDicByType('sex').then(res => {
        if (res.code === 200) {
          this.sexList = res.list
        }
      })
      getAllDicByType('marryStatus').then(res => {
        if (res.code === 200) {
          this.marryStatusList = res.list
        }
      })
    },
    sexChange (val) {
      this.data.sexShow = this.sexList.filter(v => {
        return v.key === this.data.sex
      })[0].valueCn
    },
    // 日期保存
    onBirthdayConfirm (val) {
      switch (this.showText) {
        case 'birthday':
          this.data.birthday = this.parseTime(val, '{y}-{m}-{d}')
          break
        case 'operationTime':
          this.data.operationTime = this.parseTime(val, '{y}-{m}-{d}')
          break
        default:
          break
      }
      this.isShow = false
    },
    // 手术时间
    operationTimeClick () {
      this.isShow = true
      if (this.data.operationTime) {
        this.currentDate = this.data.operationTime
      } else {
        this.currentDate = new Date()
      }
      this.showText = 'operationTime'
    },
    // 出生日期
    birthdayClick () {
      this.isShow = true
      if (this.data.birthday) {
        this.currentDate = this.data.birthday
      } else {
        this.currentDate = new Date()
      }
      this.showText = 'birthday'
    },
    // 患者分类
    typeClick () {
      this.showText = 'type'
      this.isShow = true
    },
    onTypeChange (picker, val) {
      if (this.selectVal[0] === val[0]) {
        this.selectVal = val
      } else {
        this.columns[0].values.map((v, i) => {
          if (v === val[0]) {
            const list = this.typeList[i].hospitalDepartmentList
            const columns2 = []
            list.map(v => {
              columns2.push(v.name)
            })
            this.columns[1].values = columns2
            picker.setColumnValues(1, columns2)
            this.selectVal = val
          }
        })
      }
    },
    getTypeList () {
      getDepartmentList().then(res => {
        if (res.code === 200) {
          this.typeList = res.info
          this.handlerLabel()
        }
      })
    },
    onTypeConfirm () {
      this.data.label = this.selectVal[1]
      this.isShow = false
    },
    handlerLabel () {
      let list2 = []
      if (this.typeList.length > 0) {
        if (this.data.label) {
          this.typeList.map((e1, i1) => {
            if (e1.hospitalDepartmentList && e1.hospitalDepartmentList.length > 0) {
              e1.hospitalDepartmentList.map((e2, i2) => {
                if (e2.name === this.data.label) {
                  list2 = e1.hospitalDepartmentList
                  this.columns[0].defaultIndex = i1
                  this.columns[1].defaultIndex = i2
                }
              })
            } else {
              if (e1.name === this.data.label) {
                list2 = []
                this.columns[0].defaultIndex = i1
                this.columns[1].defaultIndex = 0
              }
            }
          })
        } else {
          list2 = this.typeList[0].hospitalDepartmentList
          this.columns[0].defaultIndex = 0
          this.columns[1].defaultIndex = 0
        }
        const columns1 = []
        this.typeList.map((e1, i1) => {
          columns1.push(e1.name)
        })
        this.columns[0].values = columns1
        this.getColumns(list2)
      }
    },
    getColumns (list) {
      const columns2 = []
      list.map(v => {
        columns2.push(v.name)
      })
      this.columns[1].values = columns2
      const index1 = this.columns[0].values[this.columns[0].defaultIndex]
      const index2 = this.columns[1].values[this.columns[1].defaultIndex]
      this.selectVal = [index1, index2]
    },
    // 日期取消
    onCancel () {
      this.isShow = false
    },
    beforeRead (file) {
      if (file.size / 1024 / 1024 > 3) {
        this.$toast('单张图片大小不能超过 50MB!')
        return false
      }
      return true
    },
    afterRead (file) {
      new Promise((resolve, reject) => {
        getOssPolicy().then(res => {
          if (res.code === 200) {
            resolve(res.result)
          } else {
            this.$toast(res.msg)
          }
        })
      }).then(config => {
        const aliyunFileKey = config.dir + new Date().getTime() + Math.floor(Math.random() * 150) + '.png'
        axios.post(config.host, {
          'key': aliyunFileKey,
          'policy': config.policy, // policyBase64
          'OSSAccessKeyId': config.accessKeyId, // accessid
          'signature': config.signature, // signature
          'success_action_status': '200'
        }).then(res => {
          console.log(res)
        })
      })
    },
    onSave () {
      const formdata = Object.assign({}, this.data)
      let isOK = true
      let errmsg = ''
      const formRules = [
        { name: 'name', errmsg: '请输入姓名' },
        { name: 'sexShow', errmsg: '请选择性别' },
        { name: 'birthday', errmsg: '请选择出生日期' },
        { name: 'phone', errmsg: '请输入手机号' },
        { name: 'label', errmsg: '请选择患者分类' }
      ]
      formRules.forEach(v => {
        if (isOK) {
          if (!formdata[v.name] || formdata[v.name] === '') {
            isOK = false
            errmsg = v.errmsg
          }
        }
      })
      const phoneReg = /^1[0-9]{10,10}$/
      if (!phoneReg.test(formdata.phone)) {
        this.$toast('请输入正确的手机号')
        return false
      }
      if (!isOK) {
        this.$toast(errmsg)
        return false
      }
      formdata.patientRef[0].patientId = formdata.id
      formdata.patientRef[1].patientId = formdata.id
      formdata.healthCareCardNumber = formdata.healthCareCardNumber ? Number(formdata.healthCareCardNumber) : null
      formdata.medicalCardNumber = formdata.medicalCardNumber ? Number(formdata.medicalCardNumber) : null
      this.$toast.loading({
        message: '加载中...',
        forbidClick: true,
        overlay: true,
        duration: 0
      })
      createOrUpdateInfo(formdata).then(res => {
        this.$toast.clear()
        if (res.code === 200) {
          this.$toast.success('保存成功')
        } else {
          this.$toast(res.msg)
        }
      })
    }
  }
}
</script>
<style lang="scss">
.van-picker__cancel,
.van-picker__confirm {
  color: #03a9ac;
}
.lg-radio-group {
  display: flex;
  align-items: center;
  .van-radio {
    margin-right: 15px;
  }
}
.lg-van-cell-group {
  padding: 10px;
}
.lg-type-checkbox {
  padding: 20px;
  box-sizing: border-box;
  .van-checkbox {
    margin-bottom: 10px;
  }
}
.lg-patientInfo-btn {
  width: 90%;
  margin: 20px 5%;
}
</style>
<style lang="scss" scoped>
.lg-container {
  width: 100vw;
  min-height: 100vh;
  background-color: #f4f4f4;
  .van-doc-demo-block__title {
    margin: 0;
    padding: 20px 16px 16px;
    color: rgba(69, 90, 100, 0.6);
    font-weight: normal;
    font-size: 14px;
  }
  .lgLabel {
    text-align: left;
    color: #333333;
  }
  .placeholder-class {
    text-align: left;
  }
}
</style>
